package com.jgy.utils;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author 姜光远
 * @date 2023/3/23 11:09
 */
public class CommonUtils {


    /**
     * 计算百分比
     * @param x 分母
     * @param y 分子
     * @param type true 保留百分号 false 不保留
     * @return 结果
     */
    public String percent(int x, int y,boolean type) {
        String percent = "";
        double xx = x * 100.0;
        double yy = y * 100.0;
        double zz = xx / yy;
        DecimalFormat df = type ? new DecimalFormat("##.00%") : new DecimalFormat("0.00");
        if (Math.abs(zz) < 0.000000000001) {
            percent = type ? "0.00%" : "0.00";
        } else {
            percent = df.format(zz);
        }
        return percent;
    }


    /**
     * 获取日期当月的天数
     * @param dateStr yyyy-MM 或者 yyyy-MM-dd
     * @return int 天数
     */
    public  int getDaysByDate(String dateStr){
        int year= Integer.parseInt(dateStr.substring(0,4));
        int month=Integer.parseInt(dateStr.substring(5,7));
        Calendar c = Calendar.getInstance();
        c.set(year, month, 0);
        return c.get(Calendar.DAY_OF_MONTH);
    }


    /**
     * 测试程序
     */
    public static void main(String[] args) {
        // 构造多个时间段
        //List<TimeSegment> segments = new ArrayList<>();
        //for (int i = 0; i < 100000; i++) {
        //    segments.add(new TimeSegment(LocalDateTime.now().plusMinutes(i), LocalDateTime.now().plusMinutes(i + 1)));
        //}
        // 构造多个时间段
        List<TimeSegment> segments = new ArrayList<>();
        segments.add(new TimeSegment(LocalDateTime.parse("2023-03-23T10:00:00"), LocalDateTime.parse("2023-03-23T12:00:00")));
        segments.add(new TimeSegment(LocalDateTime.parse("2023-03-23T11:00:00"), LocalDateTime.parse("2023-03-23T13:00:00")));
        segments.add(new TimeSegment(LocalDateTime.parse("2023-03-23T14:00:00"), LocalDateTime.parse("2023-03-23T15:30:00")));
        segments.add(new TimeSegment(LocalDateTime.parse("2023-03-23T15:30:00"), LocalDateTime.parse("2023-03-23T16:30:00")));
        segments.add(new TimeSegment(LocalDateTime.parse("2023-03-23T16:00:00"), LocalDateTime.parse("2023-03-23T17:00:00")));
             //输出多个时间段
            System.out.println("多个时间段：");
            for (TimeSegment segment : segments) {
                System.out.println(segment.getStart() + " - " + segment.getEnd());
            }

        // 输出合并后的时间段
        long start = System.currentTimeMillis();
        List<TimeSegment> mergedSegments = TimeUtil.mergeTimeSegments(segments);
        long end = System.currentTimeMillis();


            // 输出合并后的时间段
            System.out.println("有效时间段：");
            for (TimeSegment segment : mergedSegments) {
                System.out.println(segment.getStart() + " - " + segment.getEnd());
            }


        System.out.println("共合并：" + mergedSegments.size() + " 个时间段，花费时间：" + (end - start) + " 毫秒");
    }
}
